package com.psbc.online_xdclass.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.psbc.online_xdclass.utils.JsonData;
import com.psbc.online_xdclass.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 这个是进入Controller之前的方法，需要在这里拦截token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            String accessToken = request.getHeader("token");
            if (accessToken == null){
                accessToken = request.getParameter("token");
            }
            if (StringUtils.isNotBlank(accessToken)){
                Claims claims = JwtUtils.checkJWT(accessToken);
                if (claims == null){
                    //返回给前端Json信息，告诉前端登录错误
                    sendJsonMessage(response, JsonData.buildError("token过期，请重新登录"));
                    return false;
                }
                Integer id =(Integer) claims.get("id");
                String name = (String) claims.get("name");
                //在请求中设置参数，可以在controller中取到，通过getAttribute()方法
                request.setAttribute("user_id",id);
                request.setAttribute("name",name);
                return true;
            }

        }catch (Exception e){}
        //返回给前端Json信息，告诉前端登录错误
        sendJsonMessage(response, JsonData.buildError("token过期，请重新登录"));
        return false;
    }
    //返回给前端Json信息
    public static void sendJsonMessage(HttpServletResponse response, Object obj){
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(objectMapper.writeValueAsString(obj));
            writer.close();
            response.flushBuffer();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
